package com.irdstudio.rsp.rule.service.impl;

import com.irdstudio.sdk.beans.core.base.FrameworkService;
import com.irdstudio.rsp.drools.beans.RuleBean;
import com.irdstudio.rsp.rule.common.BizUtil;
import com.irdstudio.rsp.rule.common.constant.Constant;
import com.irdstudio.rsp.rule.dao.BizRuleLogDao;
import com.irdstudio.rsp.rule.dao.SRuleCollInfoDao;
import com.irdstudio.rsp.rule.dao.domain.BizRuleLog;
import com.irdstudio.rsp.rule.dao.domain.SRuleCollInfo;
import com.irdstudio.rsp.rule.service.facade.BizRuleLogService;
import com.irdstudio.rsp.rule.service.vo.BizRuleLogVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
 * <p>ServiceImpl: 业务规则调用日志				<p>
 * @author AutoCoder
 * @date 2019-10-30
 */
@Service("bizRuleLogServiceImpl")
public class BizRuleLogServiceImpl implements BizRuleLogService, FrameworkService {
	
	private static Logger logger = LoggerFactory.getLogger(BizRuleLogServiceImpl.class);

	@Autowired
	private BizRuleLogDao bizRuleLogDao;

	@Autowired
    private SRuleCollInfoDao ruleCollInfoDao;
	
	/**
	 * 新增操作
	 */
	public int insertBizRuleLog(BizRuleLogVO inBizRuleLogVo) {
		logger.debug("当前新增数据为:"+ inBizRuleLogVo.toString());
		int num = 0;
		try {
			BizRuleLog bizRuleLog = new BizRuleLog();
			beanCopy(inBizRuleLogVo, bizRuleLog);
			num = bizRuleLogDao.insertBizRuleLog(bizRuleLog);
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:"+ num);
		return num;
	}

	/**
	 * 删除操作
	 */
	public int deleteByPk(BizRuleLogVO inBizRuleLogVo) {
		logger.debug("当前删除数据条件为:"+ inBizRuleLogVo);
		int num = 0;
		try {
			BizRuleLog bizRuleLog = new BizRuleLog();
			beanCopy(inBizRuleLogVo, bizRuleLog);
			num = bizRuleLogDao.deleteByPk(bizRuleLog);
		} catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ inBizRuleLogVo +"删除的数据条数为"+ num);
		return num;
	}


	/**
	 * 更新操作
	 */
	public int updateByPk(BizRuleLogVO inBizRuleLogVo) {
		logger.debug("当前修改数据为:"+ inBizRuleLogVo.toString());
		int num = 0;
		try {
			BizRuleLog bizRuleLog = new BizRuleLog();
			beanCopy(inBizRuleLogVo, bizRuleLog);
			num = bizRuleLogDao.updateByPk(bizRuleLog);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ inBizRuleLogVo +"修改的数据条数为"+ num);
		return num;
	}
	
	/**
	 * 查询操作
	 */
	public BizRuleLogVO queryByPk(BizRuleLogVO inBizRuleLogVo) {
		
		logger.debug("当前查询参数信息为:"+ inBizRuleLogVo);
		try {
			BizRuleLog queryBizRuleLog = new BizRuleLog();
			beanCopy(inBizRuleLogVo, queryBizRuleLog);
			BizRuleLog queryRslBizRuleLog = bizRuleLogDao.queryByPk(queryBizRuleLog);
			if (Objects.nonNull(queryRslBizRuleLog)) {
				BizRuleLogVO outBizRuleLogVo = beanCopy(queryRslBizRuleLog, new BizRuleLogVO());
				logger.debug("当前查询结果为:"+ outBizRuleLogVo.toString());
				return outBizRuleLogVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}


	/**
	 * 查询用户权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<BizRuleLogVO> queryAllOwner(BizRuleLogVO bizRuleLogVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		List<BizRuleLogVO> list = null;
		try {
			List<BizRuleLog> bizRuleLogs = bizRuleLogDao.queryAllOwnerByPage(bizRuleLogVo);
			logger.debug("当前查询本人所属数据信息的结果集数量为:"+ bizRuleLogs.size());
			pageSet(bizRuleLogs, bizRuleLogVo);
			list = (List<BizRuleLogVO>) beansCopy(bizRuleLogs, BizRuleLogVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<BizRuleLogVO> queryAllCurrOrg(BizRuleLogVO bizRuleLogVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		List<BizRuleLog> bizRuleLogs = bizRuleLogDao.queryAllCurrOrgByPage(bizRuleLogVo);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:"+bizRuleLogs.size());
		List<BizRuleLogVO> list = null;
		try {
			pageSet(bizRuleLogs, bizRuleLogVo);
			list = (List<BizRuleLogVO>) beansCopy(bizRuleLogs, BizRuleLogVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<BizRuleLogVO> queryAllCurrDownOrg(BizRuleLogVO bizRuleLogVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		List<BizRuleLog> bizRuleLogs = bizRuleLogDao.queryAllCurrDownOrgByPage(bizRuleLogVo);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:"+ bizRuleLogs.size());
		List<BizRuleLogVO> list = null;
		try {
			pageSet(bizRuleLogs, bizRuleLogVo);
			list = (List<BizRuleLogVO>) beansCopy(bizRuleLogs, BizRuleLogVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


    /**
     * 启新事务，用于记录规则执行结果日志
     * 避免正常流程异常，导致事务回滚
     * @param ruleBean
     * @param ruleIds
     */
    public void newTransLogBizRuleResult(RuleBean ruleBean, String req, String resp, String message) {

        String bizSerno = ruleBean.getBizSerno(); //业务流水号

        Map<String, Object> collResult = ruleBean.getOutput();
        // 执行异常日志回写
        if (collResult == null || collResult.size() == 0) {
            BizRuleLog bizRuleLog = new BizRuleLog();
            bizRuleLog.setLogId(BizUtil.getUUID("L")); // 主键
            bizRuleLog.setBizSerno(bizSerno); //业务流水号
            bizRuleLog.setAdapterOrgNo(ruleBean.getOrgNo()); // 机构id 可能空
            bizRuleLog.setAdapterPrdCode(ruleBean.getPrdCode()); // 产品代码 可能空
            bizRuleLog.setAdapterFlowId(ruleBean.getFlowId()); // 流程id 可能空
			bizRuleLog.setAdapterCustomDim1(ruleBean.getCustomDimOne());
			bizRuleLog.setAdapterCustomDim2(ruleBean.getCustomDimTwo());

            bizRuleLog.setRuleTargetType(ruleBean.getRuleCollType());
            bizRuleLog.setRequestBody(req);  // 请求报文
            bizRuleLog.setResponseBody(resp); // 返回报文
            // 超长截取 有时异常信息过长
            if (StringUtils.isNotEmpty(message) && message.length() > 80) {
                message = message.substring(0, 80);
            }
            bizRuleLog.setRuleExecResult(message); // 执行结果

            bizRuleLog.setOperTime(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            bizRuleLog.setOperUserid(StringUtils.isBlank(ruleBean.getSysCode()) ? Constant.SYS_CODE : ruleBean.getSysCode());
            // 插库
            bizRuleLogDao.insertBizRuleLog(bizRuleLog);
        } else {
            // 取去执行结果
            for (Map.Entry<String, Object> entry : collResult.entrySet()) {
                String ruleCollId = entry.getKey(); //规则集id
                Object objVal = entry.getValue(); //规则集明细执行结果 map

                Map<String, Object> collExecu = MapUtils.getMap(ruleBean.getExecu(), ruleCollId); // 规则集执行值

                BizRuleLog bizRuleLog = new BizRuleLog();
                bizRuleLog.setLogId(BizUtil.getUUID("L")); // 主键
                bizRuleLog.setBizSerno(bizSerno); //业务流水号
                bizRuleLog.setAdapterOrgNo(ruleBean.getOrgNo()); // 机构id 可能空
                bizRuleLog.setAdapterPrdCode(ruleBean.getPrdCode()); // 产品代码 可能空
                bizRuleLog.setAdapterFlowId(ruleBean.getFlowId()); // 流程id 可能空

                SRuleCollInfo collInfo = ruleCollInfoDao.queryByRuleCollId(ruleCollId);
                if (collInfo != null) {
                    bizRuleLog.setRuleTargetId(ruleCollId); // 规则集id
                    String type = collInfo.getRuleCollType();
                    bizRuleLog.setRuleTargetType(type); // 规则集类型
                    bizRuleLog.setRuleTargetName(collInfo.getRuleCollDesc()); // 规则集名称
                }

                bizRuleLog.setRequestBody(req);  // 请求报文
                bizRuleLog.setResponseBody(resp); // 返回报文
                // 超长截取 有时异常信息过长
                if (StringUtils.isNotEmpty(message) && message.length() > 80) {
                    message = message.substring(0, 80);
                }
                bizRuleLog.setRuleExecResult(message); // 执行结果

                bizRuleLog.setOperTime(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
                bizRuleLog.setOperUserid(StringUtils.isBlank(ruleBean.getSysCode()) ? Constant.SYS_CODE : ruleBean.getSysCode());
                // 插库
                bizRuleLogDao.insertBizRuleLog(bizRuleLog);
            }
        }
    }
}
